package com.kaishengit.dao.core;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class Where {
	private String property;
	private String matchType;
	private String value;
	
	public Where(String property,String matchType,String value){
		this.property =property;
		this.matchType = matchType;
		this.value = value;
	}
	public String getProperty() {
		return property;
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public String getMathType() {
		return matchType;
	}
	public void setMathType(String matchType) {
		this.matchType = matchType;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@SuppressWarnings({ "unchecked" })
	public static List<Where> builderWhereListByRequest(
			HttpServletRequest request) {
		List<Where> list = new ArrayList<Where>();
		Enumeration<String> enumeration = request.getParameterNames();
		while(enumeration.hasMoreElements()){
			String forName = enumeration.nextElement();
			if(forName.startsWith("q_")){
				String[] strs;
				if(forName.contains("_OR_")){
					strs = forName.split("_",3);
				}else{
					strs = forName.split("_");
				}
				if(strs.length<3){
					new IllegalArgumentException("未按照约束来写查询参数"+forName);
				}else{
					String property = strs[1];
					String matchType = strs[2];
					String value = request.getParameter(forName);
					if(value !=null && !value.isEmpty()){
						try {
							value = new String(value.getBytes("ISO8859-1"),"utf-8");
							//将查询参数放回request存储空间中
							request.setAttribute(forName, value);
							Where where = new Where(property, matchType, value);
							list.add(where);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}			
				}
			}
		}
		return list;
	}
	
	
}
